package dian.qing.li.demo.security.utils;

import dian.qing.li.demo.security.constants.Constants;
import lombok.experimental.UtilityClass;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 系统工具类
 *
 * @program: liqingdian
 * @description: 系统工具类
 * @author: liqingdian
 * @create: 2020-06-06 23:58
 * @Version: 1.0
 **/
@UtilityClass
public class SysUtils {

    /**
     * 获取当前request
     *
     * @Author: liqingdian
     */
    public static HttpServletRequest getRequest() {
        RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
        return ((ServletRequestAttributes) requestAttributes).getRequest();
    }

    /**
     * 获取当前response
     *
     * @Author: liqingdian
     */
    public static HttpServletResponse getResponse() {
        RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
        return ((ServletRequestAttributes) requestAttributes).getResponse();
    }

    /**
     * 获取SessionKey
     *
     * @Author: liqingdian
     */
    public static String getToken(HttpServletRequest request) {
        String authorization = request.getHeader("Authorization");
        Assert.isNotBlank(authorization, "登陆失效，请重新登陆");
        String token = StringUtils.removeStart(authorization, "Bearer ");
        return token;
    }

    /**
     * 获取SessionKey
     *
     * @Author: liqingdian
     */
    public static String getToken() {
        return getToken(getRequest());
    }

    /**
     * 获取用户编码
     *
     * @Author: liqingdian
     */
    public static String getUsername(HttpServletRequest request) {
        String username = JwtUtils.username(getToken(request), Constants.JWT_SECRET);
        Assert.isNotBlank(username, "登陆失效，请重新登陆");
        return username;
    }

    /**
     * 获取用户编码
     *
     * @Author: liqingdian
     */
    public static String getUsername() {
        return getUsername(getRequest());
    }
}
